var http = require('http');
var fs=require('fs');
var url=require('url');
var querystring = require('querystring');
var prot=8080;
var siteName ="Leaf's Message";
var ip="127.0.0.1";	
var mysql = require('mysql');
var conn = mysql.createConnection({
									host: 'localhost',
									user: 'root',
									password: '123',
									database:'messageboard',
									port: 3306
								});
conn.connect();
server=http.createServer(function (request, response) {
	response.statusCode=200;
	response.setHeader('Content-Type','text/html');
	var ext=request.url.substr(request.url.lastIndexOf('.')+1);
	var exts={
		'html':'text/html',
		'css':'text/css',
		'js':'text/javascript',
		'jpg':'image/jpeg',
		'png':'image/png'
	}
	if(exts[ext]==null){
		exts[ext]='text/plain'
	}
	response.setHeader('Content-Type',exts[ext])
	var data="404";
	var p=url.parse(request.url,true);
	if (p.pathname=='/liuyanban.html') {
		try{
			data=fs.readFileSync("."+request.url,'utf8');
			data=data.replace(/%title/g,siteName);
			/*item=fs.readFileSync('data.json','utf8');
			item=JSON.parse(item);*/
			conn.query('select * from data', function(err, rows, fields) {
			    if (err) throw err;
			    item=rows
			   	var s='';
				for (var m in item) {
					s+='<div class="item">';
					s+='<h6>'+item[m].author+'<span>'+item[m].time+'</span></h6>';
					s+='<p>'+item[m].message+'<a href="/delmessage?id='+item[m].Id+'">删除</a></p>';
					s+='</div>'
				}
				data=data.replace(/%main/g,s);
				response.write(data);
				response.end();
				});
		}catch(e){
			
		}
	}else if(p.pathname=='/form.html'){
		data=fs.readFileSync("."+request.url,'utf8');
		response.write(data);
		response.end();
	}else if(p.pathname=='/addmessage'){
		/*author=p.query.author;
		message=p.query.message;
		item=JSON.parse(fs.readFileSync('data.json','utf8'));
		//parse()用于从一个字符串中解析出json对象
		item.push({
			author:author,
			message:message,
			time:new Date()
		})
		item=JSON.stringify(item)//stringify()用于从一个对象解析出字符串
		fs.writeFileSync('data.json',item)//把item写进data.json文件里
		data="提交成功！"
		response.writeHead(302,{
			'Location':'liuyanban.html'
		});*/

		var post = '';     
 
    // 通过req的data事件监听函数，每当接受到请求体的数据，就累加到post变量中
    request.on('data', function(data){    
       post+= data;
    });



    // 在end事件触发后，通过querystring.parse将post解析为真正的POST请求格式，然后向客户端返回。
   request.on('end', function(data){    
        post= querystring.parse(post);
		conn.query('insert into data values(null,"'+post.author+'","'+post.message+'","'+new Date()+'")', function(err, rows, fields) {
		    if (err) throw err;
		    console.log(rows);
		});
     /*  item=JSON.parse(fs.readFileSync('data.json','utf8'));
       item.push({
			author:post.author,
			message:post.message,
			time:new Date()
		});
		/*item=JSON.stringify(item);*/
       /* fs.writeFileSync('data.json',JSON.stringify(item))*/
        response.writeHead(302,{
			'Location':'/liuyanban.html'
		});
			response.end();
    });
	}else if(p.pathname=='/delmessage'){
		data=p.query.id;
		/*item=JSON.parse(fs.readFileSync('data.json','utf8'));
		item.splice(data,1);
		item=JSON.stringify(item);
		fs.writeFileSync('data.json',item)*/
		conn.query('delete from data where id='+data, function(err, rows, fields) {
		    if (err) throw err;
		   response.writeHead(302,{
			'Location':'/liuyanban.html'
		});
		   response.end();	
		});	
	}
});
server.listen(prot);
console.log('Server running at http://%s:%s/',ip,prot);


